export interface RequestOptions {
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE'
  headers?: Record<string, string>
  body?: any
  params?: Record<string, any>
  showError?: boolean
}
// export const BaseUrl = 'http://zf882225.natappfree.cc'
//  expor tconst BaseUrl = 'http://zb5e67a8.natappfree.cc'
// export const BaseUrl = 'http://sensen.natapp1.cc/api'

export const BaseUrl = 'http://127.0.0.1:80/api/'
// export const BaseUrl = 'http://121.40.237.204:8888'


export async function request<T = any>(url: string, options: RequestOptions = {}): Promise<T> {
	let { method = 'GET', headers = {
		'Authorization': `Bearer ${localStorage.getItem('token')}`
	}, body, params, showError = true } = options
  let fullUrl = BaseUrl+url
  if (params && Object.keys(params).length) {
    const search = new URLSearchParams(params as any).toString()
    fullUrl += (url.includes('?') ? '&' : '?') + search
  }

  // 创建AbortController用于超时控制
  const controller = new AbortController()
  const timeoutId = setTimeout(() => {
    controller.abort()
  }, 20000) // 20秒超时

  const fetchOptions: RequestInit = {
    method,
    headers: {
      ...headers,
    },
    signal: controller.signal, // 添加signal用于取消请求
  }
  if (body) {
    if (body instanceof FormData) {
      fetchOptions.body = body
    } else if (typeof body === 'string') {
      fetchOptions.body = body
    } else {
      fetchOptions.body = JSON.stringify(body)
      fetchOptions.headers = {
        ...fetchOptions.headers,
        'Content-Type': 'application/json'
      }
    }
  }
  try {
    const res = await fetch(fullUrl, fetchOptions)
    clearTimeout(timeoutId) // 请求完成后清除超时定时器
    const data = await res.json()
    if (!res.ok || data.code === false || data.code === 500) {
      if (showError && window.messageRef?.show) {
        window.messageRef.show(data.msg || data.message || '接口请求失败', 'error')
      }
      // 新增弹窗逻辑
      const errorMsg = data.msg || data.message || '接口请求失败'
      if (window.showApiErrorDialog) {
        window.showApiErrorDialog(errorMsg)
      } else {
        window.alert(errorMsg)
        window.location.hash = '#/home'
      }
      throw new Error(errorMsg)
    }
    if (data.code === 401) {
      localStorage.removeItem('token')
       window.location.hash = '#/login'
      return undefined as unknown as T
    }
    return data.data !== undefined ? data.data : data
  } catch (e: any) {
    clearTimeout(timeoutId) // 出错时也要清除超时定时器
    
    // 检查是否是超时错误
    if (e.name === 'AbortError') {
      const timeoutMsg = '请求超时，请检查网络连接'
      if (showError && window.messageRef?.show) {
        window.messageRef.show(timeoutMsg, 'error')
      }
      // 新增弹窗逻辑
      if (window.showApiErrorDialog) {
        window.showApiErrorDialog(timeoutMsg)
      } else {
        window.alert(timeoutMsg)
        window.location.hash = '#/home'
      }
      throw new Error(timeoutMsg)
    }
    
    if (showError && window.messageRef?.show) {
      window.messageRef.show(e.message || '网络异常', 'error')
    }
    // 新增弹窗逻辑
    if (window.showApiErrorDialog) {
      window.showApiErrorDialog(e.message || '网络异常')
    } else {
      window.alert(e.message || '网络异常')
      window.location.hash = '#/home'
    }
    throw e
  }
}

// @ts-ignore
window.request = request


declare global {
  interface Window {
    request?: typeof request
    messageRef?: { show: (msg: string, type?: string) => void }
    showApiErrorDialog?: (msg: string, callback?: () => void) => void
  }
} 